<template>
  <div>
    <el-card shadow="never">
      <header-title title="其他缴费列表"></header-title>
    </el-card>
    <el-card shadow="never">
      <el-row :gutter="20">
        <el-col :offset="1" :span="20">
          <div align="right">
            <el-input
              v-model="searchForm.searchName"
              placeholder="缴费项目/商户名称/摊位号"
              size="small"
              style="margin: 0 15px 0 15px;width: 188px;"
            ></el-input>
            <span class="demonstration">缴费类型:</span>
            <el-select
              v-model="searchForm.payTypeId"
              @change="changePayType"
              placeholder="请选择"
              size="small"
              style="margin: 0 15px 0 15px;width: 145px;"
            >
              <el-option
                v-for="item in payClazzOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <span class="demonstration">缴费日期：</span>
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
            ></el-date-picker>
            <el-button
              @click="search"
              class="button"
              size="small"
              round
              icon="el-icon-search"
              style="margin: 10px 0;"
            >查询</el-button>
          </div>
        </el-col>
        <el-col :span="1">
          <el-button @click="add" class="button" size="small" round style="margin: 10px 0;">添加缴费信息</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never">
      <div>
        <el-table :data="paymentData" v-loading="loading" style="width: 100%">
          <el-table-column prop="payTheFeesTime" label="缴费时间"></el-table-column>
          <el-table-column prop="stallName" label="摊位名称"></el-table-column>
          <el-table-column prop="businessName" label="商户名称"></el-table-column>
          <el-table-column prop="stallName" label="负责人"></el-table-column>
          <el-table-column prop="stallName" label="联系电话"></el-table-column>
          <el-table-column prop="payTypeName" label="缴费项目"></el-table-column>
          <el-table-column prop="money" label="缴费金额(元)"></el-table-column>
          <el-table-column prop="content" label="备注"></el-table-column>
          <!-- <el-table-column fixed="right" label="操作" width="150">
            <template slot-scope="scope">
              <el-tooltip content="点一下就直接删除了噢" placement="top">
                <el-button @click="deletePayment(scope.row)" type="text" style="color:#f7674a;">删除</el-button>
              </el-tooltip>
            </template>
          </el-table-column>-->
          <div slot="empty">
            <img src="../../../assets/blank_tip_page/blank_tip_page.png" alt />
          </div>
        </el-table>
        <el-pagination
          :page-size="searchForm.perPage"
          :current-page="searchForm.page"
          :total="searchForm.total"
          @current-change="changePaymentPage"
          style="margin-top: 15px;"
          background
          layout="prev, pager, next"
        ></el-pagination>
      </div>
    </el-card>
    <el-dialog
      width="650px"
      title="新增缴费信息"
      :visible.sync="paymentDialog"
      @close="close"
      v-if="paymentDialog"
    >
      <div>
        <el-form :model="newPayMentModal" label-width="80px" :rules="rules" ref="newPayMentModal">
          <el-row>
            <el-col :span="12">
              <el-form-item label="商户名称" prop="businessName">
                <my-select
                  style="width:220px"
                  ref="addBusinessSelect"
                  url="api/v1/backend/public/business"
                  @selected="mySelectedBusiness"
                ></my-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="缴费通知" prop="advice" class="demonstration">
                <my-select
                  style="width:220px"
                  ref="addMessageSelect"
                  url="api/v1/backend/public/message"
                  :queryParamers="{businessId:newPayMentModal.businessId}"
                  @selected="selectedPayMessage"
                ></my-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="缴费类型" prop="type">
                <el-input v-model="newPayMentModal.payTypeName" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="金额(元)" prop="money">
                <el-input style="width:220px" v-model="newPayMentModal.money" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item style="width:100%" label="缴费信息" prop="content" class="demonstration">
                <el-input style="width:100%" v-model="newPayMentModal.content" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="账户" prop="marketAccountName">
                <el-input v-model="newPayMentModal.marketAccountName" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="缴费时间" prop="payTheFeesTime">
                <el-date-picker
                  v-model="newPayMentModal.payTheFeesTime"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="操作人" prop="actionUserName">
            <el-input v-model="newPayMentModal.actionUserName" placeholder="请填写操作人"></el-input>
          </el-form-item>
          <el-form-item label="收据信息" prop="receiptMessage">
            <el-input v-model="newPayMentModal.receiptMessage"></el-input>
          </el-form-item>
          <el-form-item label="收据照片" prop="receiptImage" ref="receiptImage">
            <!-- 需要改成可以上传照片的那样 -->
            <el-row>
              <el-col :span="5">
                <el-upload
                  class="avatar-uploader"
                  ref="playUrl"
                  style="display: inline-block;"
                  action="https://upload.qiniup.com"
                  :on-remove="handleRemove"
                  :on-success="handleSuccessplayUrl"
                  :show-file-list="false"
                  :limit="1"
                  :data="uploadToken"
                  :before-upload="beforeUpload"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-col>
              <el-col :span="19">
                <el-input v-model="newPayMentModal.receiptImage" size="medium"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPaymentInfo('newPayMentModal')">添加缴费信息</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import HeaderTitle from "@/components/HeaderTitle";
import MySelect from "@/components/MySelect";
export default {
  name: "PaymentList",
  components: {
    HeaderTitle,
    MySelect
  },
  data() {
    return {
      searchForm: {
        businessId: 0,
        searchName: "",
        payStatus: -1,
        payTypeId: -1,
        perPage: 10, // 每页显示10条
        page: 1, // 当前页
        total: 0,
        dateRange: []
      },
      loading: true,
      paymentData: [],
      paymentDialog: false,
      newPayMentModal: {
        // businessName:'',

        payTypeName: "",
        money: "",
        content: "",
        marketAccountName: "",
        payTheFeesTime: "",
        actionUserName: "",
        receiptMessage: "",
        receiptImage: ""
      },
      payStatusOptions: [],
      payClazzOptions: [],
      businessId: 1,
      uploadToken: {
        key: "",
        token: ""
      },
      rules: {
        businessName: [
          { required: true, message: "请输入商户名称", trigger: "change" }
        ],
        advice: [
          { required: true, message: "请输入缴费通知", trigger: "change" }
        ],
        payTheFeesTime: [
          { required: true, message: "请选择缴费时间", trigger: "change" }
        ],
        actionUserName: [
          { required: true, message: "请输入操作人", trigger: "blur" }
        ],
        receiptMessage: [
          { required: true, message: "请输入收据信息", trigger: "blur" }
        ],
        receiptImage: [
          { required: true, message: "请上传收据照片", trigger: "change" }
        ]
        // receiptImage: [
        //   { required: true, validator: receiptImage, trigger: ["change"] }
        // ]
      }
    };
  },
  watch: {
    "$store.state.app.marketId"(val, oldVal) {
      this.getPaymentList(this.searchForm);
      this.goodsToken();
    }
  },
  mounted() {
    this.goodsToken();
    this.initSelect();
    this.getPaymentList(this.searchForm);
  },
  methods: {
    // 是否已缴费
    changePayStatus(val) {
      this.searchForm.payStatus = val;
    },
    // 缴费类型
    changePayType(val) {
      this.searchForm.payTypeId = val;
    },

    initSelect() {
      this.$store
        .dispatch("payment/fetchPayClazz")
        .then(responseData => {
          this.payClazzOptions = responseData.data;
          this.payClazzOptions.unshift({ id: -1, name: "全部" });
        })
        .catch(err => {
          console.log(err);
        });

      this.$store
        .dispatch("payment/fetchPayStatus")
        .then(responseData => {
          this.payStatusOptions = responseData.data;
          this.payStatusOptions.unshift({ id: -1, name: "全部" });
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 获取缴费信息列表
    getPaymentList(searchForm) {
      searchForm.startDate = searchForm.dateRange[0];
      searchForm.endDate = searchForm.dateRange[1];
      console.log("searchForm", searchForm);
      this.$store
        .dispatch("payment/fetchPaymentData", searchForm)
        .then(data => {
          this.loading = false;
          for (let i = 0; i < data.items.length; i++) {
            data.items[i].money = data.items[i].money / 100;
          }
          this.paymentData = data.items;
          this.searchForm.total = data.total;
        })
        .catch(err => {
          this.loading = false;
          this.paymentData = [];
          this.searchForm.total = 0;
        });
    },
    search() {
      this.searchForm.page = 1;
      this.getPaymentList(this.searchForm);
    },
    changePaymentPage(num) {
      this.searchForm.page = num;
      this.getPaymentList(this.searchForm);
    },
    // 点击新增缴费信息
    add() {
      this.paymentDialog = true;
    },
    selectedPayMessage(obj) {
      console.log("缴费通知信息", obj);
      this.newPayMentModal = Object.assign(
        {
          businessPayTheFeesMessageDetailId: obj.value,
          content: obj.label,
          payTypeName: obj.exData.payTypeName,
          marketAccountName: obj.exData.marketAccountName,
          content: obj.exData.content,
          money: obj.exData.money / 100
        },
        this.newPayMentModal
      );
    },
    mySelectedBusiness(obj) {
      this.newPayMentModal = Object.assign(
        { businessId: obj.value, businessName: obj.label },
        this.newPayMentModal
      );
    },
    // 提交新增缴费信息
    submitPaymentInfo(newPayMentModal) {
      this.$refs[newPayMentModal].validate(valid => {
        if (valid) {
          this.paymentDialog = false;
          this.$store
            .dispatch("payment/submitPaymentInfo", this.newPayMentModal)
            .then(data => {
              console.log(data);
              this.$message({
                type: "success",
                message: "添加成功,请刷新!"
              });
              this.close();
              this.getPaymentList(this.searchForm);
            })
            .catch(err => {
              this.close();
              this.$message({
                type: "error",
                message: "添加失败，请刷新!"
              });
            });
        } else {
          this.$message.error("有必填项未填");
          return false;
        }
      });
    },
    close() {
      // 清空
      this.$refs["addBusinessSelect"].clear();
      this.$refs["addMessageSelect"].clear();
      this.newPayMentModal = {};
    },
    beforeUpload(file) {
      const isPNG = file.type === "image/png";
      const isJPEG = file.type === "image/jpeg";
      const isJPG = file.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPNG && !isJPEG && !isJPG) {
        this.$message.error("上传头像图片只能是 jpg、png、jpeg 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      //将上传的文件名保存成key,把这个key拼接到外链地址
      const date = new Date();
      this.uploadToken.key = `bill${date.getFullYear()}${date.getMonth() +
        1}${date.getDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}${Math.floor(
        Math.random() * 100
      )}.${file.type.split("/")[1]}`;
    },
    //获取上传文件时候的token
    goodsToken() {
      this.$store
        .dispatch("purchaseInfo/uptoken", {})
        .then(data => {
          this.uploadToken.token = data.data.uptoken;
        })
        .catch(err => {});
    },
    handleRemove(file, fileList) {
      console.log(file, fileList[0]);
    },
    handleSuccessplayUrl(res, file, fileList) {
      this.newPayMentModal.receiptImage =
        "http://cailanzi.image.cailanzi001.com/" + res.key;
      this.$refs.playUrl.clearFiles();
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-table__empty-text {
  width: 100%;
}
.button {
  background: #64d9d6;
  color: #fff;
  margin-left: 40px;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 33.3%;
}

/deep/ .el-form-item__label {
  text-align: right;
  float: left;
  font-size: 14px;
  color: #8492a6;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.demonstration {
  display: inline-block;
  color: #8492a6;
  font-size: 14px;
}
</style>
